package cn.iocoder.yudao.module.erp.service.accountinfo;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.erp.dal.dataobject.accountplan.AccountPlanDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.costinfo.CostInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.planinfo.PlanInfoDO;
import cn.iocoder.yudao.module.erp.dal.mysql.accountplan.AccountPlanMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.costinfo.CostInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.planinfo.PlanInfoMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.erp.controller.admin.accountinfo.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.accountinfo.AccountInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.erp.dal.mysql.accountinfo.AccountInfoMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;

/**
 * 对账单信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class AccountInfoServiceImpl implements AccountInfoService {

    @Resource
    private AccountInfoMapper accountInfoMapper;

    @Resource
    private PlanInfoMapper planInfoMapper;

    @Resource
    private AccountPlanMapper accountPlanMapper;

    @Resource
    private CostInfoMapper costInfoMapper;

    @Override
    @Transactional
    public Long addCostToAccountInfo(AccountInfoSaveReqVO createReqVO) {
       // AccountInfoDO accountInfoDO=accountInfoMapper.selectById(createReqVO.getId());

        AccountInfoDO updateObj = BeanUtils.toBean(createReqVO, AccountInfoDO.class);

        //更新cost
        if(createReqVO.getCostIds()!=null&&createReqVO.getCostIds().length>0){
            List<CostInfoDO> costList=costInfoMapper.selectList(new LambdaQueryWrapperX<CostInfoDO>().in(CostInfoDO::getId,createReqVO.getCostIds()));
            BigDecimal  costAmount= costList.stream()
                    .map(CostInfoDO::getAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            updateObj.setCostAmount(costAmount);

            costList.stream().forEach(e->{e.setAccountId(createReqVO.getId());});
            costInfoMapper.updateBatch(costList);
        }else{
            updateObj.setCostAmount(new BigDecimal("0"));
        }

        accountInfoMapper.updateById(updateObj);

        return updateObj.getId();
    }

    @Override
  /*  @Transactional*/
    public Long createAccountInfo(AccountInfoSaveReqVO createReqVO) {
        // 插入
        AccountInfoDO accountInfo = BeanUtils.toBean(createReqVO, AccountInfoDO.class);

        accountInfo.setBeginTime(createReqVO.getRangeTime()[0]);
        accountInfo.setEndTime(createReqVO.getRangeTime()[1]);

        //数据处理下
        BigDecimal gasCount=new BigDecimal("0");
        BigDecimal moneyCount=new BigDecimal("0");
        List<AccountPlanDO> list=new ArrayList<>();
        if(createReqVO.getPlanIds()!=null&&createReqVO.getPlanIds().length>0){
            List<PlanInfoDO> plans=planInfoMapper.selectList(new LambdaQueryWrapperX<PlanInfoDO>().in(PlanInfoDO::getId,createReqVO.getPlanIds()));
            //统计金额
            for(PlanInfoDO p:plans){
                if(accountInfo.getType().equals("1")){
                    //采购
                    gasCount=gasCount.add(p.getBuyRealCount());
                    moneyCount=moneyCount.add(p.getBuyAllCount());
                }else if(accountInfo.getType().equals("2")){
                    //销售
                    gasCount=gasCount.add(p.getSaleRealCount());
                    moneyCount=moneyCount.add(p.getSaleAllCount());
                }

                AccountPlanDO ap=new AccountPlanDO();
                ap.setPlanId(p.getId());
                list.add(ap);
            }
        }
        accountInfo.setAccountGasCount(gasCount);
        accountInfo.setAccountMoneyCount(moneyCount);
        accountInfo.setCompanyId(SecurityFrameworkUtils.getLoginUserDeptId());

        accountInfoMapper.insert(accountInfo);

        if(createReqVO.getPlanIds()!=null&&createReqVO.getPlanIds().length>0){
            //批量保存
            list.stream().forEach(e->{e.setAccountId(accountInfo.getId());});

            accountPlanMapper.insertBatch(list);

            //更新状态
            if(accountInfo.getType().equals("1")){
                //采购
                planInfoMapper.updateBuyStatus1ByIds(createReqVO.getPlanIds(),1);
            }else if(accountInfo.getType().equals("2")){
                //销售
                planInfoMapper.updateSaleStatus1ByIds(createReqVO.getPlanIds(),1);
            }else{
                throw exception(COMMON_EXCEPTION);
            }

        }

        // 返回
        return accountInfo.getId();
    }

    @Override
    public Long addPlanToAccount(AccountInfoSaveReqVO createReqVO) {
        // 插入
        AccountInfoDO accountInfo = accountInfoMapper.selectById(createReqVO.getId());
        PlanInfoDO p=planInfoMapper.selectById(createReqVO.getPlanId());
        if(p.getStatus()!=1){
            throw exception(new ErrorCode(1_1_1,"未结算的计划不可加入对账单！"));
        }

        //数据处理下
        BigDecimal gasCount=accountInfo.getAccountGasCount();
        BigDecimal moneyCount=accountInfo.getAccountMoneyCount();
        List<AccountPlanDO> list=new ArrayList<>();
        if(StringUtils.isNotBlank(createReqVO.getPlanId())){

            //统计金额
            if(accountInfo.getType().equals("1")){
                //采购
                gasCount=gasCount.add(p.getBuyRealCount());
                moneyCount=moneyCount.add(p.getBuyAllCount());
            }else if(accountInfo.getType().equals("2")){
                //销售
                gasCount=gasCount.add(p.getSaleRealCount());
                moneyCount=moneyCount.add(p.getSaleAllCount());
            }

            accountInfo.setAccountGasCount(gasCount);
            accountInfo.setAccountMoneyCount(moneyCount);

            accountInfoMapper.updateById(accountInfo);

            AccountPlanDO ap=new AccountPlanDO();
            ap.setPlanId(p.getId());
            ap.setAccountId(accountInfo.getId());
            accountPlanMapper.insert(ap);

            //更新状态
            if(accountInfo.getType().equals("1")){
                //采购
                planInfoMapper.updateBuyStatus1ByIds(new String[]{ap.getPlanId()+""},1);
            }else if(accountInfo.getType().equals("2")){
                //销售
                planInfoMapper.updateSaleStatus1ByIds(new String[]{ap.getPlanId()+""},1);
            }else{
                throw exception(COMMON_EXCEPTION);
            }

        }else{
            throw exception(COMMON_EXCEPTION);
        }




        // 返回
        return accountInfo.getId();
    }

    @Override
    public void updateAccountInfo(AccountInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateAccountInfoExists(updateReqVO.getId());
        // 更新
        AccountInfoDO updateObj = BeanUtils.toBean(updateReqVO, AccountInfoDO.class);
        accountInfoMapper.updateById(updateObj);
    }

    @Override
    @Transactional
    public void deleteAccountInfo(Long id) {
        // 校验存在
        //validateAccountInfoExists(id);
        // 删除
        AccountInfoDO info=accountInfoMapper.selectById(id);
        if (info == null) {
            throw exception(ACCOUNT_INFO_NOT_EXISTS);
        }
        //得到关系
        List<AccountPlanDO> list=accountPlanMapper.selectList(new LambdaQueryWrapperX<AccountPlanDO>().eq(AccountPlanDO::getAccountId,id).select(AccountPlanDO::getPlanId));
        //得到ids
        List<String> planIds=list.stream().map(e->e.getPlanId().toString()).collect(Collectors.toList());
        if(planIds!=null&&planIds.size()>0){
            String[] rids=planIds.toArray(new String[planIds.size()]);
            if(info.getType().equals("1")){
                //采购
                planInfoMapper.updateBuyStatus1ByIds(rids,0);
            }else if(info.getType().equals("2")){
                //销售
                planInfoMapper.updateSaleStatus1ByIds(rids,0);
            }else{
                throw exception(COMMON_EXCEPTION);
            }
        }


        //更新状态

        //删除对账信息
        accountPlanMapper.delete(new LambdaQueryWrapperX<AccountPlanDO>().eq(AccountPlanDO::getAccountId,id));
        //更新其他费用信息
        List<CostInfoDO> costList=costInfoMapper.selectList(new LambdaQueryWrapperX<CostInfoDO>().eq(CostInfoDO::getAccountId,id));
        if(costList!=null&&!costList.isEmpty()){
            accountInfoMapper.updateCostAccountId(id,costList.stream().map(CostInfoDO::getId).collect(Collectors.toList()));
        }

        accountInfoMapper.deleteById(id);

    }

    private void validateAccountInfoExists(Long id) {
        if (accountInfoMapper.selectById(id) == null) {
            throw exception(ACCOUNT_INFO_NOT_EXISTS);
        }
    }

    @Override
    public AccountInfoDO getAccountInfo(Long id) {
        return accountInfoMapper.selectById(id);
    }

    @Override
    public PageResult<AccountInfoDO> getAccountInfoPage(AccountInfoPageReqVO pageReqVO) {
        return accountInfoMapper.selectPage(pageReqVO);
    }

}